package com.lbd.system.service.impl;

import com.lbd.commons.exception.ControllerException;
import com.lbd.system.bean.Agreement;
import com.lbd.system.dao.AgreementRepository;
import com.lbd.system.service.AgreementService;
import com.lbd.base.service.BaseServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Map;


@Service
@Transactional
public class AgreementServiceImpl extends BaseServiceImpl<Agreement, AgreementRepository> implements AgreementService {
    private final Logger log = Logger.getLogger(this.getClass());
    @Autowired
    AgreementRepository agreementRepository;

    @Override
    public Specification<Agreement> getSpecification(Agreement agreement) {
        return null;
    }

    /**
     * 构建查询语句和参数
     *
     * @param agreement
     * @param parameter
     * @return
     */
    @Override
    public String buildJpql(Agreement agreement, Map<String, Object> parameter) {
        StringBuilder jpqlBuilder = new StringBuilder("  from  Agreement t   ");
        if (agreement != null) {

            if (StringUtils.isNotBlank(agreement.getCategory())) {
                jpqlBuilder.append(" and category =:category");
                parameter.put("category", agreement.getCategory());
            }
            if (StringUtils.isNotBlank(agreement.getTitle())) {
                jpqlBuilder.append(" and title like :title");
                parameter.put("title", "%" + agreement.getTitle() + "%");
            }
        }
        jpqlBuilder.append(" order by createdDate desc ");
        return jpqlBuilder.toString();
    }

    @Override
    public void update(Agreement agreement) {
        //校验 已发布的不允许修改
        Agreement old = agreementRepository.findOne(agreement.getId());
        if ("01".equals(old.getState())) {
            throw new ControllerException("已发布的协议不允许修改");
        }

        if (StringUtils.equals(agreement.getState(), "01")) {
            //发布
            agreement.setPublishTime(new Date());
        }

        super.update(agreement);
    }
}
